package sg.simple.snmp.provider.impl;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import org.snmp4j.CommunityTarget;
import org.snmp4j.PDU;
import org.snmp4j.Snmp;
import org.snmp4j.event.ResponseEvent;
import org.snmp4j.mp.SnmpConstants;
import org.snmp4j.smi.VariableBinding;

import sg.simple.snmp.stats.OidCode;

public class MachineSummaryInfoProvider {

	public Map<OidCode, Object> readSummary(String ipAddress, Snmp snmp,
			CommunityTarget target) throws IOException {
		PDU pdu = packGetRequest();

		ResponseEvent response = snmp.send(pdu, target);
		Map<OidCode, Object> values = new HashMap<OidCode, Object>();

		if (response != null && response.getResponse() != null) {

			if (response.getResponse().getErrorStatus() == SnmpConstants.SNMP_ERROR_SUCCESS) {
				PDU pduResponse = response.getResponse();

				for (int i = 0; i < pduResponse.getVariableBindings().size(); i++) {

					VariableBinding variableBinding = pduResponse
							.getVariableBindings().elementAt(i);
					OidCode code = OidCode.getByOid(variableBinding.getOid());
					values.put(code, variableBinding.getVariable().toString());

				}
			} else {
				throw new IOException(
						"Unable to retrieve machine information due to - "
								+ response.getResponse().getErrorStatusText());
			}

		} else {

			throw new IOException(
					"Unable to retrieve machine information from : "
							+ ipAddress + " - request timed out");
		}

		return values;
	}

	private PDU packGetRequest() {
		// creating PDU
		PDU pdu = new PDU();
		pdu.add(new VariableBinding(OidCode.SYSTEM_DESCRIPTION.getOid()));
		pdu.add(new VariableBinding(OidCode.NETWORK_UPTIME.getOid()));
		pdu.add(new VariableBinding(OidCode.HOST_UPTIME.getOid()));
		pdu.add(new VariableBinding(OidCode.CONTACT_PERSON_FOR_SYSTEM.getOid()));
		pdu.add(new VariableBinding(OidCode.NUMBER_OF_USER_SESSIONS.getOid()));
		pdu.add(new VariableBinding(OidCode.NUMBER_OF_PROCESS_CONTEXTS.getOid()));
		pdu.add(new VariableBinding(OidCode.SYSTEM_NAME.getOid()));
		pdu.add(new VariableBinding(OidCode.SYSTEM_LOCATION.getOid()));
		pdu.add(new VariableBinding(OidCode.NUMBER_OF_NETWORK_INTERFACES
				.getOid()));
		pdu.add(new VariableBinding(OidCode.MEMORY_IN_KILO_BYTES.getOid()));

		pdu.setType(PDU.GET);
		return pdu;
	}

}
